<template>
    <div class="container">
      <div class="sidebar">
        <!-- <el-tree 
        :data="deviceList" 
        :props="dPs" 
        @node-click="handleNodeClick" 
        :current-node-key='currentKey' 
        default-expand-all 
        :highlight-current="highlightBd"
        node-key="id"
        ref="treeRef"
        ></el-tree> -->
        <div class="selected"></div>
        <el-dropdown  @command="handleCommand" style="
        cursor: pointer;
        font-weight: 500;
        font-size: 16px;
        line-height: 1;
        letter-spacing: 0.09px;
        color: #202224;">
          
          <el-button style="margin-top: 10px; margin-left:10px">
            传感器<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown"  type="primary" @click="handleClickDevice">
              <el-dropdown-item v-for="item in deviceList" :key="item.value" :command="item">{{ item.name }}</el-dropdown-item>
              <!-- <el-dropdown-item>狮子头</el-dropdown-item>
              <el-dropdown-item>螺蛳粉</el-dropdown-item>
              <el-dropdown-item disabled>双皮奶</el-dropdown-item>
              <el-dropdown-item divided>蚵仔煎</el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="content">
        <!-- activeName -->
        <el-tabs v-model="activeName"  @tab-click="handleClick">
          <!-- <el-button @click="getList"> get</el-button> -->
        
          <el-tab-pane :label="`雨量数据图 ${choseDeviceName}`" name="first">
            <div class="chart-container">
              <chart v-loading="loading" height="100%" width="100%" :chartData="chartData" :chartRiqi="chartRiqi" />
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="降雨速率图" name="second"></el-tab-pane> -->
          <!-- <el-tab-pane label="刨面内侧点缩略图" name="third"></el-tab-pane> -->
        </el-tabs>
      </div>
      
      
    </div>
  </template>
  
  <script>
  import chart from '../../components/charts/Mix-rain.vue'
  import { getDeviceRainData, listDevice, listNewDevice, sensorPointList  } from "@/api/screen/device";
  
  export default {
    name: 'graph',
    components: { chart },
    data() {
      return {
        currentKey: 0 ,
        activeName: 'first',
        chartData: [
          // 150, 230, 224, 218, 135
          // 10, 10, 10, 1, 1, 1, 1

        ],
        choseDeviceName: '',
        chartRiqi: [
          // '2023-11-11', '2023-11-12', '2023-11-13', '2023-11-14', '2023-11-15'
        ],
        deviceRainDataList: [],
        highlightBd: true,
        deviceList: [],
        activeName: 'first',
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        elTreeData: [],
        loading: true,
        sensorPointList:[],
        username: ''
        // groupedDevices: {}
      }
    },
    computed: {
      dPs() {
        return {
          children: 'children',
          label: 'label'
        };
      },
    },
    mounted() {
      // this.getList()
      // this.getListNew()
      // this.checkedKeys = 124
      this.username = this.$store.state.user.name

      if(this.username == 'maguan') {
        this.getsensorPoint('马关')
      }
      else if (this.username == 'guanxi'){
        this.getsensorPoint('关西')
      }
      else {
        this.getsensorPoint()
      }

      // this.getsensorPoint('关西')
      console.log('username', this.username)
    },
    // created() {
    //  this.loading = true;
    // //  this.fetchDeviceIdAndList();
    // },
    methods: {
         //站点列表
      getsensorPoint(e) {
        sensorPointList({ name: e, sensorName: '雨量'}).then(response=> {
          this.deviceList = response.rows
          console.log('deviceListRain',this.deviceList ) 
          // this.convertToElTree()
          // this.groupByDeviceId()
          // 选择并处理第一个树节点
          // if (this.deviceList?.length > 0 && this.deviceList[0].children && this.deviceList[0].children?.length > 0) {
          //   const firstNodeId = this.deviceList[0].children[0].id;
          //   this.handleNodeClick({id: firstNodeId});
          // }

          console.log('this.deviceList', this.deviceList)
          // monitordevicecode 所属监测点
          // monitordevicename 设备类型
          // deviceid  设备id
          this.total = response.total;
          this.loading = false;

        })
      },
      handleClick (tab, event) {
        console.log(tab, event)
      },
       /** 查询设备列表 */
      getList() {
        this.loading = true;
        listNewDevice({resultData:'rainData',pageSize:100}).then(response => {
          
          // this.deviceList = myList
          
          this.deviceList = response.rows
          console.log('deviceList',response.rows) 
        // let new_arr = this.deviceList.map(obj => {return obj.resultData})
        //   console.log('new_arr',new_arr)
        // // let rain_arr = this.deviceList.map(obj => {return obj.rainData})
        // let a = new_arr.indexOf("rainData")
        //   console.log('a',a)
          // this.groupByDeviceId()
          
            // 选择并处理第一个树节点
          if (this.deviceList.length > 0 && this.deviceList[0].children && this.deviceList[0].children.length > 0) {
            const firstNodeId = this.deviceList[0].children[0].id;
            console.log('firstNodeId',firstNodeId)
            this.handleNodeClick({id: firstNodeId});

             this.convertToElTree()
            console.log('this.deviceList', this.deviceList)
            console.log('123',firstNodeId,this.currentKeys)
          }
            this.groupByDeviceId()

            // this.convertToElTree()
            // console.log('this.deviceList', this.deviceList)
            // monitordevicecode 所属监测点
            // monitordevicename 设备类型
            // deviceid  设备id
            //this.total = response.total;
            //this.loading = false;
          }).catch(error => {
          console.error("Error fetching device list:", error);
          this.loading = false;
        }
      );
      },
      
      /** 查询降雨量设备数据详情 */
      getDeviceRainData(e) {
        this.loading = true;
        getDeviceRainData({deviceId:e, isAsc:'desc', orderByColumn:'createTime'}).then(response => {
          console.log('deviceRainDataList',response.rows) 
          this.loading = false
          // let resList = response.rows
          this.deviceRainDataList = response.rows
          // this.deviceRainDataList = resList.reverse()
          // this.chartRiqi = this.deviceRainDataList.map(item=> {return item.createTime})
          console.log('this.chartRiqi', this.chartRiqi)
          this.chartData = this.deviceRainDataList.map(item=> {return item.resultData})
          this.chartRiqi = this.deviceRainDataList.map(item=> {return item.createTime})
          console.log('this.chartData, waibu', this.chartData)
          console.log('this.chartRiqi, waibu', this.chartRiqi)
          }
        );
      },
      handleNodeClick(deviceList) {
        console.log('deviceList',deviceList, deviceList.id);
        if( deviceList.id == null) {
          console.log('null')
        } else {
          this.getDeviceRainData(deviceList.deviceId)
          this.currentKey = deviceList.deviceId
          this.$nextTick(() => {
            this.$refs['treeRef'].setCurrentKey(this.currentKey)
          })
        }
      },
      // 函数根据 deviceId 对设备进行分组
      groupByDeviceId(devices = this.deviceList) {
        return devices.reduce((groups, device) => {
          const { deviceId } = device;
          if (!groups[deviceId]) {
            groups[deviceId] = [];
          }
          groups[deviceId].push({
            label: device.deviceName,
            ...device
          });
          console.log('groups', groups)
          this.groupedDevices = groups


          // 将分组转换为 el-tree 的数据格式（每个分组一个树）
          this.deviceList = Object.keys(this.groupedDevices).map(deviceId => {
            return {
              label: `位置编号 ${deviceId}`,
              children: this.groupedDevices[deviceId],
              
              // children: this.groupedDevices[{ id: device.deviceId, label: device.deviceName  }]
            };
          });
          return groups;
        }, {});
      },

      // 使用groupByDeviceId函数进行分组
      // const groupedDevices = groupByDeviceId(deviceList);

      // 将分组转换为 el-tree 的数据格式（每个分组一个树）
      // const treesData = Object.keys(groupedDevices).map(deviceId => {
      //   return {
      //     label: `设备编号 ${deviceId}`,
      //     children: groupedDevices[deviceId]
      //   };
      // });

      convertToElTree(e = this.deviceList) {
          const tempMap = new Map(); // 临时 Map 用于合并相同项
          // 遍历设备列表
          e.forEach(device => {
            if (tempMap.has(device.monitorDeviceCode) ) {
               // 如果存在相同设备名称的项，则合并
               const existingDevice = tempMap.get(device.monitorDeviceCode);
              //  const existingMonitordevicename = tempMap.get(device.monitordevicename);
               existingDevice.children.push({ id: device.deviceId, label: device.deviceName });
            } else {
               // 如果不存在相同设备名称的项，则创建新节点
               tempMap.set(device.monitorDeviceCode, {
                label: device.monitorDeviceCode,
                
                children: [{ id: device.deviceId, label: device.deviceName  }]
              });
              // 如果不存在相同设备名称的项，则创建新节点
              
            }
          });
          
          // 将 Map 转换为数组，存储到 elTreeData 中
          this.elTreeData = Array.from(tempMap.values());

          this.deviceList = this.elTreeData
          console.log('this.elTreeData', this.elTreeData)
        },
      handleCommand(command) {
          console.log('command', command)
          this.choseDeviceName = command.name
          listNewDevice({strPointId: command.strId, pageSize:500, isAsc: 'desc',orderByColumn: 'time'}).then(response => {
            console.log('deviceLevelDataList',response.rows) 
            
            this.loading = false
            // let resList = response.rows
            // this.deviceLevelDataList = resList.reverse()
            this.deviceLevelDataList = response.rows
            this.chartRiqi = this.deviceLevelDataList.map(item=> {return item.time})
            this.chartData = this.deviceLevelDataList.map(item=> {return ((item.resultData.substr(0, item.resultData.length-1)).split(':'))[1] })
            console.log('this.chartData0', this.chartData)
            // this.chartData[0]
            console.log('this.chartData1', this.chartData[0])

            // let length = (this.chartData[0]).length -1

            // console.log('this.chartData123456', this.chartData[0].substr(0,length))
            // var n = Array.from(chartData,({name})=>name);
            // console.log('n', n)
            // this.getNewArr(this.chartData)
            console.log('this.chartData2', this.chartData)
            console.log('this.chartRiqi',  this.chartRiqi)
          }
        )
      },

   
      handleClickDevice(e) {
        console.log('eeeeeeeeeeeeeeeee', e)
      }
  }
}
  </script>
  
  <style  lang="scss">

  /* .el-tree-node:focus > .el-tree-node__content {
    background-color: #66b1ff87 !important;
  }
  .el-tree-node__content:hover {    background-color: #66b1ff87;
  }
  .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color: #66b1ff87;
  } */

.container .sidebar {
  // 修改高亮背景色和color
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    // background-color: #fcf5f3;
    color: #409eff;
  }
  // .el-tree-node:focus > .el-tree-node__content {
  //   color:  #409eff;
  //   /* transition: background 1s; */
  // }
}
  
  
  
  /* .container .sidebar {
    .el-tree-node:focus > .el-tree-node__content {
      background-color: rgba(135, 206, 235, 0.3);
      color: #409eff; //节点的字体颜色
      font-weight: bold;
    }
  } */


.container {
    display: flex;
  }

    
  .sidebar {
    width: 200px; /* Adjust the width as per your layout */
    height: 100vh;
  }
  
  .content {
    flex: 1;
    height: 100vh;
  }
  

  .chart-container{
  position: relative;
  width: 100%;
  height: 80vh;
}

.selected {
  color: #409eff;
}

  </style>